package edu.zzuli.assistant.api.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import edu.zzuli.assistant.bean.Follow;
import edu.zzuli.assistant.bean.User;
import edu.zzuli.assistant.service.FollowService;
import edu.zzuli.assistant.service.UserService;
import edu.zzuli.assistant.service.impl.FollowServiceImpl;
import edu.zzuli.assistant.service.impl.UserServiceImpl;
import edu.zzuli.assistant.until.StrUtil;

public class UserAction extends ActionSupport implements ModelDriven,SessionAware{
	
	private UserService userService=new UserServiceImpl();
	private FollowService followService = new FollowServiceImpl();
	private Map<String, Object> session;
	private User user;
	private List<User> userList;// 用户集合
	private List<Follow> followList;// 已关注的人集合
	private int page =1;//当前页数 默认第一页
	private String[]  fields = {"id","name","focus","authorId","followNum","fansNum","intro","headUrl","status","newsNum","newReply"};

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}
	public List<Follow> getFollowList() {
		return followList;
	}

	public void setFollowList(List<Follow> followList) {
		this.followList = followList;
	}
	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}	
	public Map<String, Object> getSession() {
		return session;
	}
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

	@Override
	public Object getModel() {
		// TODO Auto-generated method stub
		if(user==null){
			this.user= new User();
		}
		return user;
	} 
	
    
    // 登录验证
    public void login(){
    	
    	HttpServletRequest request = ServletActionContext.getRequest();
    	HttpServletResponse response = ServletActionContext.getResponse();
    	String key= request.getParameter("key");
    	// 用key 防止外来密码破解  key="abced"
    	if(key!=null && "iec_wq2014".equals(key)){
    		if(user.getId()!=null && user.getPassword()!=null){
    			
    			boolean result=userService.login(user); 
    			if(result){
    				session.clear();
        			user = userService.getUserBaseInfo(user.getId());
        			session.put("userId", user.getId());
        			session.put("userName", user.getName());
        			session.put("status", user.getStatus());
        			StrUtil.sendJson(User.class, fields, user);
    			}else{
    				StrUtil.sendMsg("fail");
    			}
    		}
    	}
    }
    
    // 退出
    public void logOut(){
    	session.clear();
    }
    
    public void teacher(){
    	
		userList = userService.getTeacherList(page, 10);
    	//找出已关注的人
    	if(session.get("userId")!=null){
    		String userId= session.get("userId").toString();
    		followList = followService.getStartList(userId);
    		List<User> userList2 = new ArrayList<User>();
    		List<String> list = new ArrayList<String>();
    		for(Follow follow :followList){
    			list.add(follow.getStartId());
    		}
    		for(User user :userList){
    			if(list.contains(user.getId())){
    				user.setFocus(true);
    			}
    			userList2.add(user);
    		}
    		StrUtil.sendJson(User.class, fields, userList2);
    		return;
    	}
    	StrUtil.sendJson(User.class, fields, userList);
    }
    public void publicnum(){
    	
    	userList = userService.getPublicList(page, 10);
    	//找出已关注的人
    	if(session.get("userId")!=null){
    		String userId= session.get("userId").toString();
    		followList = followService.getStartList(userId);
    		List<User> userList2 = new ArrayList<User>();
    		List<String> list = new ArrayList<String>();
    		//User user = new User()
    		for(Follow follow :followList){
    			list.add(follow.getStartId());
    		}
    		for(User user :userList){
    			//followList.
    			if(list.contains(user.getId())){
    				user.setFocus(true);
    			}
    			userList2.add(user);
    		}
    		StrUtil.sendJson(User.class, fields, userList2);
    		return;
    	}
    	StrUtil.sendJson(User.class, fields, userList);
    }
    
    // 粉丝
    public void fans(){
    	
    	if(session.get("userId")!=null){
    		String userId= session.get("userId").toString();
    		userList = followService.getFansUserList(userId,page, 10);
    		followList = followService.getStartList(userId);
    		List<User> userList2 = new ArrayList<User>();
    		List<String> list = new ArrayList<String>();
    		
    		for(Follow follow :followList){
    			list.add(follow.getStartId());
    		}
    		for(User user :userList){
    			if(list.contains(user.getId())){
    				user.setFocus(true);
    			}
    			userList2.add(user);
    		}
    		StrUtil.sendJson(User.class, fields, userList2);
    		return;
    	}
    	StrUtil.sendMsg(LOGIN);
    }
    //找出我关注的人
    public void following(){
    	
    	if(session.get("userId")!=null){
    		String userId= session.get("userId").toString();
    		userList = followService.getStartUserList(userId,page, 10);
    		List<User> userList2 = new ArrayList<User>();
    		for(User user :userList){
    			user.setFocus(true);
    			userList2.add(user);
    		}
    		StrUtil.sendJson(User.class, fields, userList2);
    		return;
    	}
    	StrUtil.sendMsg(LOGIN);
    }
    

	//搜索教师
	public  void seek_teacher(){
		
		userList =userService.getUserByName(user.getName(),User.STATUS_TREACHER,page, 10);
		
    	//找出已关注的人
    	if(session.get("userId")!=null){
    		String userId= session.get("userId").toString();
    		followList = followService.getStartList(userId);
    		List<User> userListFollow = new ArrayList<User>();
    		List<String> list = new ArrayList<String>();
    		//User user = new User()
    		for(Follow follow :followList){
    			list.add(follow.getStartId());
    		}
    		for(User user :userList){
    			//followList.
    			if(list.contains(user.getId())){
    				user.setFocus(true);
    			}
    			userListFollow.add(user);
    		}
    		StrUtil.sendJson(User.class, fields, userListFollow);
    		return;
    	}
    	StrUtil.sendJson(User.class, fields, userList);
	}
	
	//搜索公众号
	public void seek_pub(){
		
		userList =userService.getUserByName(user.getName(),User.STATUS_PUBLIC,page, 10);
    	//找出已关注的人
    	if(session.get("userId")!=null){
    		String userId= session.get("userId").toString();
    		followList = followService.getStartList(userId);
    		List<User> userListFollow = new ArrayList<User>();
    		List<String> list = new ArrayList<String>();
    		//User user = new User()
    		for(Follow follow :followList){
    			list.add(follow.getStartId());
    		}
    		for(User user :userList){
    			//followList.
    			if(list.contains(user.getId())){
    				user.setFocus(true);
    			}
    			userListFollow.add(user);
    		}
    		StrUtil.sendJson(User.class, fields, userListFollow);
    		return;
    	}
    	StrUtil.sendJson(User.class, fields, userList);
		
	}
    
    
	// 更新简介 modifyIntro.action
	public void modify_intro(){
		if(session.get("userId")!=null){
			
			if(user.getIntro()==null || user.getIntro().length()>35){
				StrUtil.sendMsg(ERROR);
				return ;
			}
			String userId= session.get("userId").toString();
			boolean result = userService.modifyIntro(userId, user.getIntro()); 
			if(result){
				StrUtil.sendMsg("success");
			}
			else{
				StrUtil.sendMsg("fail");
			}
		}
		StrUtil.sendMsg(LOGIN);
		
	}
	// 更新邮箱
	public void modify_email(){
		if(session.get("userId")!=null){
			
			if(user.getEmail()==null ||user.getPassword()==null ||! isEmail(user.getEmail()) ){
				
				StrUtil.sendMsg(ERROR);
				return ;
			}
			user.setId(session.get("userId").toString());
			
			if(userService.selectByEmail(user.getEmail())!=null){
				
				StrUtil.sendMsg("exist");
				return  ;//已经存在该 邮箱
			}
			boolean result = userService.updateEmail(user); 
			if(result){
				StrUtil.sendMsg("success");
			}
			else{
				StrUtil.sendMsg("fail");
			}
		}
		else{
			
			StrUtil.sendMsg(LOGIN);
		}
		
	}
	
	// 更新密码 modifyIntro.action
	public void modify_password(){
		if(session.get("userId")!=null){
			HttpServletRequest request = ServletActionContext.getRequest();
			user.setId(session.get("userId").toString());
			String newPassword = request.getParameter("newPassword");
			
			if(newPassword ==null || newPassword.length()<6|| newPassword.length()>12){
				StrUtil.sendMsg(ERROR);
				return;
			}
    		boolean result=userService.login(user); 
    		if (result) {
    			result = userService.modifyPassword(user, newPassword);
    			if(result){
    				StrUtil.sendMsg(SUCCESS);
    			}
    			else{
    				StrUtil.sendMsg("fail");
    			}
    		} else {
    			StrUtil.sendMsg(ERROR);
    		}
    		return;
		}
		StrUtil.sendMsg(LOGIN);
	}
	// 邮箱正则表达式
    public boolean isEmail(String email){     
           String str="^([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)*@([a-zA-Z0-9]*[-_]?[a-zA-Z0-9]+)+[\\.][A-Za-z]{2,3}([\\.][A-Za-z]{2})?$";
           Pattern p = Pattern.compile(str);     
           Matcher m = p.matcher(email);     
           return m.matches();    
      } 

}

